<?php

namespace XWAM\Addon\PXCallSystem\Controller;

/**
 * 内线控制器
 *
 * @author Alen
 */
class ExtensionController extends AppbaseController {

    public function seat_list() {
        $M = M('tuser_member');
        $M->execute('update tuser_member set personalName=concat("座席",extensionNumber) where personalName is null;');
        $M->execute('update tuser_member set ctiModel="SEAT" where ctiModel is null;');
        $this->display();
    }

    public function get_seat_search_data() {
        $search = I();
        // 查询条件
        $where['userType'] = 'SEAT';
        if ($search['userName']) {
            $where['userName'] =array('in',$search['userName']) ;
        }
        if ($search['teamNumber']) {
            $where['teamNumber'] = $search['teamNumber'];
        }
        if (!$this->isSuperAdmin) {
            $where['siteID'] = $this->loginData['siteID'];
        }
        return array('where' => $where);
    }

    public function get_seat_list_json() {
        $search_data = $this->get_seat_search_data();
        $list = AddonD('Extension')->get_seat_list($search_data['where']);
        $this->ajaxReturn($list);
    }

    public function seat_export() {
        $search_data = $this->get_seat_search_data();
        $list = AddonD('Extension')->scope('seat_export')->where($search_data['where'])->select();
        if (!$list) {
            $this->ajaxMsg(false, '找不到符合条件的记录!');
        }
        sofn_excel_export($list);
    }

    public function extension_list() {
        $M = M('tuser_member');
        $M->execute('update tuser_member set personalName=concat("座席",extensionNumber) where personalName is null;');
        $M->execute('update tuser_member set ctiModel="SEAT" where ctiModel is null;');
        $this->display();
    }

    public function get_extension_search_data() {
        $search = I();
        $where['userType'] = 'SEAT';
        if ($search['userName']) {
            $where['userName'] = array('in',$search['userName']) ;
        }
        if ($search['ctiTrunk']) {
            $where['ctiTrunk'] = $search['ctiTrunk'];
        }
        if (!$this->isSuperAdmin) {
            $where['siteID'] = $this->loginData['siteID'];
        }
        return array('where' => $where);
    }

    public function get_extension_list_json() {
        $search_data = $this->get_extension_search_data();
        $list = AddonD('Extension')->get_extension_list($search_data['where']);
        $this->ajaxReturn($list);
    }

    public function extension_export() {
        $search_data = $this->get_extension_search_data();
        $list = AddonD('Extension')->scope('extension_export')->where($search_data['where'])->select();
        if (!$list) {
            $this->ajaxMsg(false, '找不到符合条件的记录!');
        }
        sofn_excel_export($list);
    }

    /**
     * 获取分机列表
     */
    public function get_extension_json() {
        $where['userType'] = "SEAT";
        if ($this->isSuperAdmin) {
            if (I('siteID')) {
                $where['siteID'] = I('siteID');
            }
        } else {
            $where['siteID'] = $this->loginData['siteID'];
        }
        $arr = AddonD('Extension')->where($where)->field('extensionNumber as id, extensionNumber as text')->select();
        $this->ajaxReturn($arr);
    }

    public function seat_edit($id = 0) {
        if ($id) {
            $data = AddonD('Extension')->find($id);
            $this->assign('data', $data);
        }
        $this->display();
    }

    public function forwarding_edit() {
        $cw = I('cw');
        $id = I('id');
        if (!$id) {
            $this->ajaxMsg(false, '参数无效!', '', $cw != 'N');
        }
        $data = M('tuser_member')->find($id);
        if ($data['userType'] != 'SEAT') {
            $this->ajaxMsg(false, '不是有效的座席!', '', $cw != 'N');
        }
        $this->assign('data', $data);
        $this->display();
    }

    public function forwarding_edit_save() {
        $id = I('id');
        $extension = I('extension');
        if (!$extension) {
            $this->ajaxMsg(false, '分机无效');
        }
        $forwardingState = I('forwardingState');
        $forwardingExtension = I('forwardingExtension');
        if ($forwardingState == '') {
            $this->ajaxMsg(false, '条件未选择');
        }

        $forwardingStateOld = I('forwardingStateOld');
        $forwardingExtensionOld = I('forwardingExtensionOld');
        $M = M('tuser_member');
        $arrCode = array('', 'CF', 'CFB', 'CFU');
        $astman = create_asmanager();

        if ($forwardingExtension == '') {
            // 如果分机号为空且已经有转移记录则退出转移
            if ($forwardingStateOld !== '') {
                $result = $astman->database_del($arrCode[$forwardingStateOld ? $forwardingStateOld : $forwardingState], $extension);
                if ($result) {
                    $M->where("id=$id")->setField(array('forwardingState' => '', 'forwardingExtension' => ''));
                }
                $this->ajaxMsg($result, '退出转移{%}!');
            }
            $this->ajaxMsg(false, '转移分机未选择!');
        }
        if ($forwardingState == '4') {
            $astman->database_del('CF', $extension);
            $astman->database_del('CFB', $extension);
            $result = $astman->database_del('CFU', $extension);
            $M->where("id=$id")->setField(array('forwardingState' => '', 'forwardingExtension' => ''));
            $this->ajaxMsg(true, '退出转移{%}!');
        }

        if (($forwardingExtensionOld == $forwardingExtension) && ($forwardingStateOld == $forwardingState)) {
            $this->ajaxMsg(true, '无需操作!');
        }
        $result = $M->where("id=$id")->setField(array('forwardingState' => $forwardingState, 'forwardingExtension' => $forwardingExtension));
        if (false === $result) {
            $this->ajaxMsg(false, '数据库保存失败!');
        }

        // 分机或状态改变的时候,退出上一个分机和状态,设置本次分机和状态
        if (($forwardingExtensionOld && $forwardingExtensionOld !== $forwardingExtension) || ($forwardingStateOld && $forwardingStateOld !== $forwardingState)) {
            $result = $astman->database_del($arrCode[$forwardingStateOld], $extension);
            sleep(1);
            //echo 'database del ' . $arrCode[$forwardingStateOld] . ' ' . $extension;
        }
        $result = $astman->database_put($arrCode[$forwardingState], $extension, $forwardingExtension);
        //echo 'database put ' . $arrCode[$forwardingState] . ' ' . $extension . ' ' . $forwardingExtension;
        $this->ajaxMsg($result, '保存{%}!');
    }

    public function extension_edit($id = 0) {
        $M = M('tuser_member');
        $sipPort = $M->where("userName='ADMIN' and userType='SUPERADMIN'")->getField('sipPort');
        if (!$sipPort) {
            $sipPort = C('CTI_PORT');
        }
        $data = false;
        if ($id) {
            $data = M('tuser_member')->find($id);
            if (!$data['sipPort']) {
                $data['sipPort'] = $sipPort;
            }
        } else {
            $data = array('sipPort' => $sipPort);
        }
        $this->assign('data', $data);
        $this->assign('guide', I('guide'));
        $this->assign('batch', I('batch'));
        $this->display();
    }

    public function extension_delete($id = '') {
        if (!$id) {
            $this->ajaxMsg(false, '参数有误!');
        }
        $M = new \Think\Model\AdvModel('tuser_member');
        $names = $M->where("id in ($id)")->getField('userName', true);
        $result = $M->where("id in ($id)")->delete();
        $msg = '删除失败';
        if (false !== $result) {
            $strNames = implode(',', $names);
            $arrSqls = array(
                "delete from asterisk.sip where id in ($strNames);",
                "delete from asterisk.users where extension in ($strNames)",
                "delete from asterisk.devices where id in ($strNames)",
                "delete from asterisk.cxpanel_users where user_id in ($strNames)");
            $M->patchQuery($arrSqls);
            foreach ($names as $name) {
                $msg = $this->Activate(array('extension' => $name), 0, 4);
            }
            if ($msg === true) {
                $msg = $this->active_recordState($names, 4, '');
            }
            if ($msg === true) {
                $this->force_need_reload(false);
                $this->ajaxMsg(true, '删除成功!');
            }
        }
        $this->ajaxMsg(false, $msg);
    }

    public function seat_password_reset($id = 0) {
        if (!$id) {
            $this->ajaxMsg(false, '参数有误!');
        }
        $pwd = '123456';
        $result = M('tuser_member')->where('id=' . $id)->setField('password', $pwd);
        $this->ajaxMsg($result, '密码重置{%}');
    }

    public function seat_save() {
        $params = new \Org\Su\Params();
        $params->addParam('userName', 'require', '账户名必须填写!');
        $params->addParam('state', 'number', '状态有误!');
        $params->addParam('personalName', 'require', '姓名有误!');
        $params->addParam('ctiModel', 'require', '班长模式有误!');
        $params->addParam('teamNumber', 'number', '队列号码有误!');
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }

        $id = I('id');
        if ($id) {
            $result = M('tuser_member')->where("id=$id")->save($params->getParams());
        }
        $this->ajaxMsg($result, '保存{%}!');
    }

    public function extension_batch_edit($id = '') {
        if (!$id) {
            die('参数有误');
        }
        $list = M('tuser_member')->where(array('id' => array('in', $id)))->field('id,userName, ctiCallerNo')->select();
        $this->assign('list', $list);
        $this->display();
    }

    public function extension_batch_edit_save() {
        $ids = I('id');
        $ctiCallerNos = I('ctiCallerNo');
        $i = 0;
        foreach ($ids as $id) {
            $ctiCallerNo = $ctiCallerNos[$i];
            $sqls[] = "update tuser_member set ctiCallerNo='$ctiCallerNo' where id=$id";
            $i++;
        }
        M()->clear_table_caching('tuser_member');
        $M = new \Think\Model\AdvModel();
        $M->patchQuery($sqls);
        $this->ajaxMsg(true);
    }

    public function seat_batch_edit($id = '') {
        if (!$id) {
            die('参数有误');
        }
        $list = M('tuser_member')->where(array('id' => array('in', $id)))->field('id,userName, personalName,ctiModel')->select();
        $this->assign('list', $list);
        $this->display();
    }

    public function seat_batch_edit_save() {
        $ids = I('id');
        $personalNames = I('personalName');
        $i = 0;
        foreach ($ids as $id) {
            $personalName = $personalNames[$i];
            $ctiModel = I('ctiModel'.$id);
            $sqls[] = "update tuser_member set personalName='$personalName', ctiModel='$ctiModel' where id=$id";
            $i++;
        }
        M()->clear_table_caching('tuser_member');
        $M = new \Think\Model\AdvModel();
        $M->patchQuery($sqls);
        $this->ajaxMsg(true);
    }

    public function extension_save() {
        $batch = I('batch');
        $id = I('id');
        $M = M('tuser_member');
        if (!$id) {
            $arr = get_licence_data();
            if ($M->where("userType='SEAT'")->count() > $arr['agent']) {
                $this->ajaxMsg(false, '超过服务器最大工号数量限制!');
            }
        }
        $params = new \Org\Su\Params();
        $params->addParam('siteID', 'number', '租户未选择!');
        $params->addParam('userName', 'require', '分机号必须填写!');
        if ($batch) {
            $params->addParam('userName2', 'require', '结束分机号必须填写!');
        }
        $params->addParam('sipPort', 'number', '注册端口必需填写!');
        $params->addParam('extensionPassword', 'require', '密码必须填写!');
        $params->addParam('ctiTrunk', 'require', '中继号码必须选择!', true);
        $params->addParam('ctiCallerNo', 'require', '主叫号码必须填写!', true);
        $params->addParam('ctiRegMode', 'require', '中继注册模式必须填写!', true);
        $params->addParam('recState', 'number', '录音标识必须选择!');
        $params->addParam('dtmfmode', 'require', 'dtmfmode必须选择!');
        $params->addParam('canreinvite', 'require', 'canreinvite必须选择!');
        $params->addParam('state', 'number', '状态有误!');
        $userName = I('userName');
        $userName2 = I('userName2');
        if ($userName) {
            if (strlen($userName) > 4) {
                $params->addError('分机号必须是小于或等于4位!');
            }
            if (intval($userName[0]) < 2 || intval($userName[0]) == 9) {
                $params->addError('分机号必须以2以上的数字开头且不包含9!');
            }
        }
        if ($userName2 && intval($userName2) < intval($userName)) {
            $params->addError('结束分机号不能小于开始分机号!');
        }
        $params->addData('dialopts_cb');
        if (I('dialopts_cb')) {
            $params->addParam('dialopts', 'require', 'dialopts未填写');
        } else {
            $params->addData('dialopts', '');
        }
        if ($params->hasError()) {
            $this->ajaxMsg(false, $params->getError());
        }

        if ($batch) {
            for ($i = $userName; $i <= $userName2; $i++) {
                $names[] = $i;
            }
            if ($names) {
                // 检测用户名是否重复
                $exists = $M->where(sprintf("userName in ('%s')", implode("','", $names)))->getField('userName');
                if ($exists) {
                    $names = array_diff($names, $exists);
                }
            }
        } else {
            $names[] = $userName;
            if (!$id) {
                // 检测用户名是否重复
                if ($M->where("userName='$userName'")->count() > 0) {
                    $this->ajaxMsg(false, '[' . $userName . '] 已存在!');
                }
            }
        }
        $trunk = I('ctiTrunk');
        $caller = I('ctiCallerNo');
        $siteID = I('siteID');
        // 编辑模式
        if ($id) {
            $params->addData('id', $id);
            $result = $M->save($params->getParams(array('userName')));
            if (false !== $result) {
                $msg = $this->progress_asterisk_data($userName, true);
                if ($msg !== true) {
                    $this->ajaxMsg(false, $msg);
                }
                $astman = create_asmanager();
                $astman->Command("sip reload users all");
                $this->force_need_reload(false);
            }
        } else {
            $result = true;
            // 新增模式
            foreach ($names as $name) {
                $data = $params->getParams();
                // 如果是新增用户则座席则分机号就是用户名
                $data['userName'] = $name;
                $data['extensionNumber'] = $name;
                $data['createdTime'] = date('Y-m-d H:i:s');
                $data['userType'] = 'SEAT';
                $data['ctiCallerNo'] = $caller ? $caller : $name;
                $data['password'] = '123456';
                if (false === $M->add($data)) {
                    $result = false;
                } else {
                    $msg = $this->progress_asterisk_data($name, false);
                }
            }
            $astman = create_asmanager();
            $astman->Command("sip reload users all");
            $astman->Command("dialplan reload");
            $this->force_need_reload(false);
        }
        if (false === $result) {
            $this->ajaxMsg(false, '保存失败');
        }
        $this->ajaxMsg(true, '保存成功');
    }

    // 2014-11-6 by sutroon
    function progress_asterisk_data($userName, $hasId) {
        $data['extension'] = $userName;
        $data['extensionPassword'] = I('extensionPassword');
        $data['dtmf'] = I('dtmfmode');
        $data['canreinvite'] = I('canreinvite');
        $data['ctiCallerNo'] = I('ctiCallerNo');
        $data['dialopts'] = I('dialopts');
        $data['sipPort'] = I('sipPort');
        $result = $this->save_asterisk($data, $hasId ? 'update' : 'add');

        if ($result === false) {
            $this->ajaxMsg(false, '更新CTI基础服务失败!');
        } else {
            $recState = I('recState');
            if ($hasId) {
                $msg = $this->active_recordState($userName, $recState, $data['ctiCallerNo'], $data['dialopts']);
                return $msg;
            } else {
                $this->add_dialplan_conf($userName);
                $msg = $this->active_recordState($userName, $recState, $data['ctiCallerNo'], $data['dialopts']);
                $msg = $this->Activate($data, 1, $recState);
                return $msg;
            }
        }
    }

    public function active_recordState($extension, $recState, $ctiCallerNo, $dialopts = 'Tttg') {
        $astman = create_asmanager();
        if ($recState == '4') {
            if (is_array($extension)) { // 允许数组
                foreach ($extension as $u) {
                    $astman->Command('database deltree ampuser ' . $u);
                }
            } else {
                $astman->Command('database deltree ampuser ' . $extension);
            }
        } else {

            // $astman->database_put("AMPUSER",$extension."/password",isset($password)?$password:'');
            $astman->database_put("AMPUSER", $extension . "/ringtimer", 0);
            $astman->database_put("AMPUSER", $extension . "/cfringtimer", 0);
            $astman->database_put("AMPUSER", $extension . "/concurrency_limit", 0);
            $astman->database_put("AMPUSER", $extension . "/noanswer", "\"\"");
            $astman->database_put("AMPUSER", $extension . "/recording", "\"\"");
            $astman->database_put("AMPUSER", $extension . "/cidname", $extension);
            $astman->database_put("AMPUSER", $extension . "/cidnum", $extension);
            $astman->database_put("AMPUSER", $extension . "/voicemail", "novm");
            $astman->database_put("AMPUSER", $extension . "/answermode", "\"disabled\"");

            $rec_external = $recState == '1' ? 'always' : 'never';
            $rec_ondemand = $recState == '1' ? 'enabled' : 'disabled';
            $astman->database_put("AMPUSER", $extension . "/recording/in/external", "\"$rec_external\"");
            $astman->database_put("AMPUSER", $extension . "/recording/out/external", "\"$rec_external\"");
            $astman->database_put("AMPUSER", $extension . "/recording/in/internal", "\"$rec_external\"");
            $astman->database_put("AMPUSER", $extension . "/recording/out/internal", "\"$rec_external\"");
            $astman->database_put("AMPUSER", $extension . "/recording/ondemand", "\"$rec_ondemand\"");
            $astman->database_put("AMPUSER", $extension . "/recording/priority", "\"0\"");
            if ($dialopts == 'Tttg' || $dialopts == '') {
                unset($dialopts);
            }
            if (isset($dialopts)) {
                $astman->database_put("AMPUSER", $extension . "/dialopts", $dialopts);
            } else {
                $astman->database_del("AMPUSER", $extension . "/dialopts");
            }
            $callwaiting = 'enabled'; // 2014-11-27 检查##转分机时新增
            if (trim($callwaiting) == 'enabled') {
                $astman->database_put("CW", $extension, "\"ENABLED\"");
            } else if (trim($callwaiting) == 'disabled') {
                $astman->database_del("CW", $extension);
            }

            $astman->database_put("AMPUSER", $extension . "/ccss/cc_agent_policy", "\"generic\"");
            $astman->database_put("AMPUSER", $extension . "/ccss/cc_offer_timer", "\"30\"");
            /* $astman->database_put("AMPUSER", $extension . "/ccss/last_number", 0); */
            $astman->database_put("AMPUSER", $extension . "/device", $extension);
            $astman->database_put("AMPUSER", $extension . "/language", "\"\"");
            $astman->database_put("AMPUSER", $extension . "/password", "\"\"");
            $astman->database_put("AMPUSER", $extension . "/queues/qnostate", "\"usestate\"");


            $astman->database_put("DEVICE", $extension . "/default_user", $extension);
            $astman->database_put("DEVICE", $extension . "/dial", "SIP/" . $extension);
            $astman->database_put("DEVICE", $extension . "/type", "\"fixed\"");
            $astman->database_put("DEVICE", $extension . "/user", $extension);
            // "\"610\"<610>"
            //$astman->database_put('AMPUSER/' . $extension . '/recording/out', 'external', ($recState == '1' ? 'always' : 'dontcare'));
            $astman->database_put("AMPUSER", $extension . "/outboundcid", $ctiCallerNo ? "\\\"$ctiCallerNo\\\"<$ctiCallerNo>" : '');
        }
        return true;
    }

    /**
     * 保存到asterisk数据库
     * @param array $data
     * @param string $mode 模式,add=新增,update=更新
     * @since 1.0 2014-7-4 by sutroon
     */
    function save_asterisk($data, $mode) {
        $a = new \Think\Model\AdvModel();
        $result = $a->patchQuery($this->get_save_asterisk_sql($data, $mode));
        if ($result === false) {
            die($a->getDbError());
        }
        return $result;
    }

    /**
     * 获取注册asterisk的写入语句
     * @param array $data
     * @param string $mode add=新增,update=更新
     * @return array
     */
    protected function get_save_asterisk_sql($data, $mode) {
        $extension = $data['extension'];
        $sip = array(
            'secret' => $data['extensionPassword'],
            'dtmfmode' => $data['dtmf'], // rfc2833
            'canreinvite' => $data['canreinvite'],
            'context' => 'xcall', // from-internal
            'host' => 'dynamic',
            'type' => 'friend',
            'nat' => 'yes',
            'port' => $data['sipPort'],
            'qualify' => 'yes',
            'callgroup' => '',
            'pickupgroup' => '',
            'disallow' => '',
            'allow' => '',
            'dial' => 'SIP/' . $extension,
            'accountcode' => '',
            'mailbox' => $extension . '@device',
            'deny' => '0.0.0.0/0.0.0.0',
            'permit' => '0.0.0.0/0.0.0.0',
            'account' => $extension . '',
            'callerid' => 'device <' . $extension . '>',
            'encryption' => 'no',
            'qualifyfreq' => 60,
            'sendrpid' => 'pai',
            'transport' => 'udp',
            'trustrpid' => 'yes',
                // 'record_in' => 'Adhoc',
                // 'record_out' => 'Adhoc',
                // 'avpf' => 'no', // 2014-11-27 查找##转分机问题时候注释
                // 'icesupport' => 'no', // 2014-11-27 查找##转分机问题时候注释
        );

        $outboundcid = $data['ctiCallerNo'] ? '"' . $data['ctiCallerNo'] . '"<' . $data['ctiCallerNo'] . '>' : '';
        $arr = array();
        // $recording='out=Adhoc|in=Adhoc';  // 2014-11-27 查找##转分机问题时候注释
        $recording = '';
        if ($mode == 'update') {
            foreach ($sip as $k => $v) {
                $arr[] = "update asterisk.sip set data='$v' where id='$extension' and keyword='$k';";
            }
            $arr[] = "update asterisk.users set password='', name='$extension', voicemail='novm', ringtimer=0, noanswer= '', recording='$recording', outboundcid='$outboundcid', sipname='' where extension='$extension';";
            $arr[] = "update asterisk.devices set tech='sip', dial='SIP/$extension', devicetype='fixed', user='$extension', description='$extension', emergency_cid='' where id='$extension';";
            $arr[] = "update asterisk.cxpanel_users set user_id='$extension', display_name='$extension', peer='SIP/$extension', add_extension=0, full=0, add_user=0, hashed_password='798a14afea8f52759da9b6f90aa0f1b3fb8e0a49', initial_password='xrQdHFK6gn', auto_answer=0, parent_user_id='$extension', password_dirty=0 where user_id='$extension';";
        } else {
            $i = 2;
            foreach ($sip as $k => $v) {
                $arr[] = "insert into asterisk.sip (id, keyword, data,flags) values ('$extension','$k','$v',$i);";
                $i++;
            }
            $arr[] = "insert into asterisk.users (extension, password, name, voicemail, ringtimer, noanswer, recording, outboundcid, sipname) values ('$extension', '', '$extension', 'novm', 0, '', '$recording', '$outboundcid', '');";
            $arr[] = "insert into asterisk.devices (id,tech, dial, devicetype, user, description,emergency_cid) values ('$extension', 'sip','SIP/$extension', 'fixed', '$extension', '$extension', '');";
            $arr[] = "insert into asterisk.cxpanel_users (user_id, display_name, peer, add_extension, full, add_user, hashed_password, initial_password, auto_answer, parent_user_id, password_dirty) values ('$extension', '$extension', 'SIP/$extension', 0, 0, 0, '798a14afea8f52759da9b6f90aa0f1b3fb8e0a49', 'xrQdHFK6gn', 0, '$extension', 0);";
        }
        return $arr;
    }

    function Activate($data, $activated = true, $recState = '') {
        //return true;
        if (!file_exists(sip_additional_path)) {
            return '配置文件不存在';
        }
        if (!is_writable(sip_additional_path)) {
            return '配置文件不允许读写';
        }

        $file_content = file_get_contents(sip_additional_path);
        if ($activated) {
            if (strstr($file_content, '[' . $data['extension'] . ']')) {
                return '配置文件中已包含此分机' . $data['extension'];
            }
            $content = sip_additional_tpl;
            $content = str_replace("{user_extension}", $data["extension"], $content);
            $content = str_replace("{mailbox}", $data["extension"], $content);
            $content = str_replace("{canreinvite}", $data["canreinvite"], $content);
            $content = str_replace("{secret}", $data["extensionPassword"], $content);
            $content = str_replace("{context}", 'xcall', $content);
            $fp = fopen(sip_additional_path, 'a+');
            fwrite($fp, $content);
            fclose($fp);
        } else {
            if (strstr($file_content, '[' . $data['extension'] . ']')) {
                $file_content = ereg_replace('\[' . $data['extension'] . '[^\[]*[^\[]?', "", $file_content);
                file_put_contents(sip_additional_path, $file_content);
            }
        }
        return true;
    }

    /**
     * @param $extension
     * @since 1.0 2014-11-6 by sutroon
     */
    public function add_dialplan_conf($extension) {
        $path = '/etc/asterisk/extensions_additional.conf';
        $content = file_get_contents($path);
        $firstExtension = M('tuser_member')->where("userType='SEAT'")->order('id')->getField('userName');

        if (false === strpos($content, 'exten => ' . $extension . ',hint,')) {
            $str = 'exten => ###,1,Set(__RINGTIMER=${IF($[${DB(AMPUSER/###/ringtimer)} > 0]?${DB(AMPUSER/###/ringtimer)}:${RINGTIMER_DEFAULT})})' . PHP_EOL . 'exten => ###,n,Macro(exten-vm,novm,###,0,0,0)' . PHP_EOL . 'exten => ###,n(dest),Set(__PICKUPMARK=)' . PHP_EOL . 'exten => ###,n,Goto(${IVR_CONTEXT},return,1)' . PHP_EOL . 'exten => ###,hint,SIP/###&Custom:DND###';
            $content = str_replace('exten => vmret,', str_replace('###', $extension, $str), $content) . PHP_EOL . PHP_EOL . 'exten => vmret,';
        }


        file_put_contents($path, $content);
        return; // 不继续执行
        // [ext-dnd-hints]
        if (false === strpos($content, 'exten => *76' . $extension . ',1,Goto(app-dnd-toggle,*76,1)')) {
            $str = 'exten => *76' . $extension . ',1,Goto(app-dnd-toggle,*76,1)' . PHP_EOL . 'exten => *76' . $extension . ',hint,Custom:DEVDND' . $extension . PHP_EOL . PHP_EOL . ';--== end of [ext-dnd-hints] ==--;';
            $content = str_replace(';--== end of [ext-dnd-hints] ==--;', $str, $content);
        }

        // [park-hints]
        if (false === strpos($content, 'exten => *85' . $extension . ',1,Macro(parked-call,,default)')) {
            $str = 'exten => *85' . $extension . ',1,Macro(parked-call,,default)' . PHP_EOL . 'exten => *85' . $extension . ',hint,Custom:PARK' . $extension . '' . PHP_EOL . PHP_EOL . ';--== end of [park-hints] ==--;';
            $content = str_replace(';--== end of [park-hints] ==--;', $str, $content);
        }

        // [from-did-direct-ivr]
        if (false === strpos($content, 'exten => ' . $extension . ',1,Macro(blkvm-clr,)')) {
            $str = 'exten => ' . $extension . ',1,Macro(blkvm-clr,)' . PHP_EOL . 'exten => ' . $extension . ',n,Set(__NODEST=)' . PHP_EOL . 'exten => ' . $extension . ',n,Goto(from-did-direct,' . $extension . ',1)' . PHP_EOL . PHP_EOL . ';--== end of [from-did-direct-ivr] ==--;';
            $content = str_replace(';--== end of [from-did-direct-ivr] ==--;', $str, $content);
        }

        // [from-queue-exten-only]
        if (false === strpos($content, 'exten => ' . $extension . ',1,Set(RingGroupMethod=none)')) {
            $str = 'exten => ' . $extension . ',1,Set(RingGroupMethod=none)' . PHP_EOL . 'exten => ' . $extension . ',n,Set(QDOPTS=${IF($["${CALLER_DEST}"!=""]?g)}${IF($["${AGENT_DEST}"!=""]?F(${AGENT_DEST}))})' . PHP_EOL . 'exten => ' . $extension . ',n(checkrecord),Gosub(sub-record-check,s,1(exten,' . $extension . '))' . PHP_EOL . 'exten => ' . $extension . ',n,Macro(dial-one,,${DIAL_OPTIONS}${QDOPTS},' . $extension . ')' . PHP_EOL . 'exten => ' . $extension . ',n,GotoIf($["${CALLER_DEST}"!=""]?${CUT(CALLER_DEST,^,1)},${CUT(CALLER_DEST,^,2)},${CUT(CALLER_DEST,^,3)})' . PHP_EOL . 'exten => ' . $extension . ',n,Hangup' . PHP_EOL . PHP_EOL . 'exten => h,1,Macro(hangupcall,)' . PHP_EOL . PHP_EOL . ';--== end of [from-queue-exten-only] ==--;';
            $content = str_replace('exten => h,1,Macro(hangupcall,)' . PHP_EOL . PHP_EOL . ';--== end of [from-queue-exten-only] ==--;', $str, $content);
        }

        // [ext-cf-hints]
        if (false === strpos($content, 'exten => *740' . $extension . ',1,Goto(app-cf-toggle,*740,1)')) {
            $str = 'exten => *740' . $extension . ',1,Goto(app-cf-toggle,*740,1)' . PHP_EOL . 'exten => *740' . $extension . ',hint,Custom:DEVCF' . $extension . '' . PHP_EOL . PHP_EOL . 'exten => _*740' . $extension . '.,1,Set(toext=${EXTEN:7})' . PHP_EOL . 'exten => _*740' . $extension . '.,n,Goto(app-cf-toggle,*740,setdirect)' . PHP_EOL . PHP_EOL . ';--== end of [ext-cf-hints] ==--;';
            $content = str_replace(';--== end of [ext-cf-hints] ==--;', $str, $content);
        }
        // ;--== end of [ext-queues] ==--;
        $str = 'exten => *46*' . $extension . ',1,Goto(app-all-queue-pause-toggle,s,1)';
        if (false === strpos($content, $str) && false !== ($pos = strrpos($content, ',1,Goto(app-all-queue-pause-toggle,s,1)'))) {
            $len = strlen(',1,Goto(app-all-queue-pause-toggle,s,1)');
            $content = substr($content, 0, $pos + $len) . PHP_EOL . PHP_EOL . $str . PHP_EOL . substr($content, $pos + $len);
        }
        $str = 'exten => *45*' . $extension . ',1,Goto(app-all-queue-toggle,s,start)';
        if (false === strpos($content, $str) && false !== ($pos = strrpos($content, ',1,Goto(app-all-queue-toggle,s,start)'))) {
            $len = strlen(',1,Goto(app-all-queue-toggle,s,start)');
            $content = substr($content, 0, $pos + $len) . PHP_EOL . PHP_EOL . $str . PHP_EOL . substr($content, $pos + $len);
        }

        // ;--== end of [ext-intercom-users] ==--;
        $str = 'exten => *80' . $extension . ',1,Goto(ext-intercom,${EXTEN},1)';
        if (false === strpos($content, $str) && false !== ($pos = strrpos($content, ',1,Goto(ext-intercom,${EXTEN},1)'))) {
            $len = strlen(',1,Goto(ext-intercom,${EXTEN},1)');
            $content = substr($content, 0, $pos + $len) . PHP_EOL . PHP_EOL . $str . PHP_EOL . PHP_EOL . substr($content, $pos + $len);
        }

        // ;--== end of [ext-local] ==--;

        $str = 'exten => 300,1,Set(__RINGTIMER=${IF($[${DB(AMPUSER/300/ringtimer)} > 0]?${DB(AMPUSER/300/ringtimer)}:${RINGTIMER_DEFAULT})})';

        $str = 'exten => ' . $extension . ',hint,SIP/' . $extension . '&Custom:DND' . $extension;
        if (false === strpos($content, $str) && (false !== ($pos = strpos($content, 'exten => vmret,1,GotoIf($["${IVR_RETVM}" = "RETURN" & "${IVR_CONTEXT}" != ""]?playret)')))) {
            $len = strlen('exten => vmret,1,GotoIf($["${IVR_RETVM}" = "RETURN" & "${IVR_CONTEXT}" != ""]?playret)');
            $str = 'exten => ' . $extension . ',1,Set(__RINGTIMER=${IF($[${DB(AMPUSER/' . $extension . '/ringtimer)} > 0]?${DB(AMPUSER/' . $extension . '/ringtimer)}:${RINGTIMER_DEFAULT})})' . PHP_EOL . 'exten => ' . $extension . ',n,Macro(exten-vm,novm,' . $extension . ',0,0,0)' . PHP_EOL . 'exten => ' . $extension . ',n(dest),Set(__PICKUPMARK=)' . PHP_EOL . 'exten => ' . $extension . ',n,Goto(${IVR_CONTEXT},return,1)' . PHP_EOL . 'exten => ' . $extension . ',hint,SIP/' . $extension . '&Custom:DND' . $extension;
            $content = substr($content, 0, $pos) . PHP_EOL . $str . PHP_EOL . PHP_EOL . PHP_EOL . substr($content, $pos);
        }

        // ;--== end of [ext-findmefollow] ==--;
        $str = 'exten => *21' . $extension . ',hint,Custom:FOLLOWME' . $extension . '';
        if (false === strpos($content, $str) && (false !== ($pos = strpos($content, 'exten => FM')))) {
            $len = strlen('exten => FM');
            $str = 'exten => *21' . $extension . ',1,Goto(app-fmf-toggle,*21,1)' . PHP_EOL . 'exten => *21' . $extension . ',hint,Custom:FOLLOWME' . $extension . '';
            $content = substr($content, 0, $pos) . $str . PHP_EOL . PHP_EOL . PHP_EOL . substr($content, $pos);
        }
        $str = 'exten => FM' . $extension . ',1,Goto(' . $extension . ',FM' . $extension . ')';
        if (false === strpos($content, $str)) {
            $str = '' . PHP_EOL . 'exten => FM' . $extension . ',1,Goto(' . $extension . ',FM' . $extension . ')' . PHP_EOL . PHP_EOL . 'exten => ' . $extension . ',1,GotoIf($[ "${DB(AMPUSER/' . $extension . '/followme/ddial)}" = "EXTENSION" ]?ext-local,' . $extension . ',1)' . PHP_EOL . 'exten => ' . $extension . ',n(FM' . $extension . '),Macro(user-callerid,)
' . PHP_EOL . 'exten => ' . $extension . ',n,Set(DIAL_OPTIONS=${DIAL_OPTIONS}I)' . PHP_EOL . 'exten => ' . $extension . ',n,Set(CONNECTEDLINE(num)=' . $extension . ')' . PHP_EOL . 'exten => ' . $extension . ',n,Set(CONNECTEDLINE(name,i)=${DB(AMPUSER/' . $extension . '/cidname)})' . PHP_EOL . 'exten => ' . $extension . ',n,Set(FM_DIALSTATUS=${EXTENSION_STATE(' . $extension . '@ext-local)})' . PHP_EOL . 'exten => ' . $extension . ',n,Set(__EXTTOCALL=${EXTEN})' . PHP_EOL . 'exten => ' . $extension . ',n,Set(__PICKUPMARK=${EXTEN})' . PHP_EOL . 'exten => ' . $extension . ',n,Macro(blkvm-setifempty,)' . PHP_EOL . 'exten => ' . $extension . ',n,GotoIf($["${GOSUB_RETVAL}" = "TRUE"]?skipov)' . PHP_EOL . 'exten => ' . $extension . ',n,Macro(blkvm-set,reset)' . PHP_EOL . 'exten => ' . $extension . ',n,Set(__NODEST=)' . PHP_EOL . 'exten => ' . $extension . ',n(skipov),Set(RRNODEST=${NODEST})' . PHP_EOL . 'exten => ' . $extension . ',n(skipvmblk),Set(__NODEST=${EXTEN})' . PHP_EOL . 'exten => ' . $extension . ',n,GosubIf($[${DB_EXISTS(AMPUSER/' . $extension . '/followme/changecid)} = 1 & "${DB(AMPUSER/' . $extension . '/followme/changecid)}" != "default" & "${DB(AMPUSER/' . $extension . '/followme/changecid)}" != ""]?sub-fmsetcid,s,1())' . PHP_EOL . 'exten => ' . $extension . ',n,Set(RecordMethod=Group)' . PHP_EOL . 'exten => ' . $extension . ',n(checkrecord),Gosub(sub-record-check,s,1(exten,' . $extension . ',))' . PHP_EOL . 'exten => ' . $extension . ',n,GotoIf($[$[ "${DB(AMPUSER/' . $extension . '/followme/prering)}" = "0" ] | $[ "${DB(AMPUSER/' . $extension . '/followme/prering)}" = "" ]] ?skipsimple)' . PHP_EOL . 'exten => ' . $extension . ',n,Macro(simple-dial,' . $extension . ',${DB(AMPUSER/' . $extension . '/followme/prering)})' . PHP_EOL . 'exten => ' . $extension . ',n(skipsimple),Set(RingGroupMethod=)' . PHP_EOL . 'exten => ' . $extension . ',n,Set(_FMGRP=' . $extension . ')' . PHP_EOL . 'exten => ' . $extension . ',n(DIALGRP),GotoIf($[("${DB(AMPUSER/' . $extension . '/followme/grpconf)}"="ENABLED") | ("${FORCE_CONFIRM}"!="") ]?doconfirm)' . PHP_EOL . 'exten => ' . $extension . ',n,Macro(dial,${DB(AMPUSER/' . $extension . '/followme/grptime)},${DIAL_OPTIONS},${DB(AMPUSER/' . $extension . '/followme/grplist)})' . PHP_EOL . 'exten => ' . $extension . ',n,Goto(nextstep)' . PHP_EOL . 'exten => ' . $extension . ',n(doconfirm),Macro(dial-confirm,${DB(AMPUSER/' . $extension . '/followme/grptime)},${DIAL_OPTIONS},${DB(AMPUSER/' . $extension . '/followme/grplist)},' . $extension . ')' . PHP_EOL . 'exten => ' . $extension . ',n(nextstep),Set(RingGroupMethod=)' . PHP_EOL . 'exten => ' . $extension . ',n,GotoIf($["foo${RRNODEST}" != "foo"]?nodest)' . PHP_EOL . 'exten => ' . $extension . ',n,Set(__NODEST=)' . PHP_EOL . 'exten => ' . $extension . ',n,Set(__PICKUPMARK=)' . PHP_EOL . 'exten => ' . $extension . ',n,Macro(blkvm-clr,)' . PHP_EOL . 'exten => ' . $extension . ',n,Set(DIALSTATUS=${IF($["${FM_DIALSTATUS}"="NOT_INUSE"&"${DIALSTATUS}"!="CHANUNAVAIL"]?NOANSWER:${IF($["${DIALSTATUS}"="CHANUNAVAIL"|"${FM_DIALSTATUS}"="UNAVAILABLE"|"${FM_DIALSTATUS}"="UNKNOWN"|"${FM_DIALSTATUS}"="INVALID"]?CHANUNAVAIL:BUSY)})})' . PHP_EOL . 'exten => ' . $extension . ',n,Hangup' . PHP_EOL . 'exten => ' . $extension . ',n(nodest),Noop(SKIPPING DEST, CALL CAME FROM Q/RG: ${RRNODEST})' . PHP_EOL . PHP_EOL . ';--== end of [ext-findmefollow] ==--;';
            $content = str_replace(';--== end of [ext-findmefollow] ==--;', $str, $content);
        }
    }

}
